import React, { PureComponent } from 'react';
import { connect } from 'dva';
import $ from 'jquery';
import { Icon, Card, Table, Input, message, Tag, Tooltip } from 'antd';
import url from 'url';
import querystring from 'querystring';
import styles from './ShopPool.less';
import { searchStatistic, searchTaobaoShop, queryQumai, queryShopPools } from '../../services/tool';
import KXIcons from '../NicaiPool/Columns/KXIcons';
import KXShopLevel from '../NicaiPool/Columns/KXShopLevel';

const Search = Input.Search;
@connect(state => ({
  currentUser: state.user.currentUser,
}))
export default class ShopPool extends PureComponent {
  state = {
    auctions: [],
    loading: false,
    shopsLoading: false,
    searchValue: '',
    shopPool: [],
    num: 0,
    shops: [],
  }

  componentWillMount () {
    queryShopPools().then(shopPool => {
      this.setState({
        shopPool,
      });
    });
  }
  handleSearch = () => {
    const { currentUser } = this.props;
    const { shopPool, searchValue, auctions } = this.state;
    let valueInp = searchValue;
    if (!valueInp) {
      message.warn('请输入要搜索的关键词或商品链接');
      return;
    } else if (/(https?|ftp|file):\/\/[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]/.test(valueInp)) {
      valueInp = escape(valueInp);
    }
    this.setState({
      auctions: [],
      shops: [],
      num: 0,
      loading: true,
      shopsLoading: true,
    });
    for (let i = 0; i < shopPool.length; i ++) {
      ((pool) =>{
        const kxuan_url = url.parse(pool.kxuan_url);
        const query = querystring.parse(kxuan_url.query);
        let search_url = `https://kxuan.taobao.com/searchSp.htm?ajax=true&callback=jsonp2711&q=${
        valueInp}&${kxuan_url.query}&nested=we&number=${Math.random()}`;
        // console.log(search_url);
        const newPool = {...pool, kxuan_url_with_q: `${pool.kxuan_url}&q=${valueInp}`};
        $.ajax({
          url: search_url,
          dataType: 'jsonp',
          type: 'get',
          success: (data) => {
            const aryAuctions = (data["mods"] && data["mods"]["itemlist"]) ? data["mods"]["itemlist"]["data"]["auctions"] : []; // object
            let auctions = [ ...this.state.auctions ];
            // console.log(auctions);
            if (aryAuctions.length >= 1) {
              aryAuctions.forEach(item => {
                const auct = auctions.find(item1 => item1.detail_url === item.detail_url);
                if (!auct) {
                  auctions.push({...item, pools: [newPool]});
                } else {
                  // const po = auct.pools.find(item2 => item2.kxuan_url === newPool.kxuan_url);
                  // if (!po) auct.pools.push(newPool);
                  auct.pools.push(newPool);
                }
                this.searchGoodGoods(item);
              });
            }
            this.setState({
              loading: false,
              num: this.state.num + 1,
              auctions,
            }, () => {
              if (this.state.num === shopPool.length) {
                const tempAuctions = [];
                this.state.auctions.forEach(item => {
                  if (!tempAuctions.find(item1 => item1.shopLink === item.shopLink)) {
                    tempAuctions.push(item);
                  }
                });
                tempAuctions.forEach(item => {
                  this.searchTaobaoShop(item);
                });
                if (this.state.auctions.length === 0) {
                  message.info('未找到');
                }
              }
            });
          },
          error:function(XMLHttpRequest, textStatus, errorThrown) {

          }
        });
      })(shopPool[i]);
    }
    searchStatistic({
      name: '查询店铺池子',
      user_id: currentUser._id,
      username: currentUser.name,
    });
  }
  searchTaobaoShop = (auction) => {
    // console.log(auction.shopLink);
    const urlObj = url.parse(auction.shopLink);
    const query = querystring.parse(urlObj.query);
    searchTaobaoShop(query).then(result => {
      // console.log(auction.shopLink);
      // console.log(result);
      const shops = [...this.state.shops];
      const shop = shops.find(item => item.url === result.url);
      if (!shop) {
        shops.push(result);
        this.setState({ shops, shopsLoading: false });
      }
    });
  }
  searchGoodGoods = (auction) => {
    queryQumai({text: auction.detail_url}).then(result => {
      // console.log(auction.shopLink);
      // console.log(result);
      let goodGoods = '';
      const innerText = result.data.htmls
      if (innerText) {
        goodGoods = innerText.split('有好货已入库')[1].split('条')[0]
      }
      // console.log(goodGoods);
      const auctions = [...this.state.auctions];
      const index = auctions.findIndex(item => item.detail_url === auction.detail_url);
      if (index >= 0) {
        auctions[index].goodGoods = goodGoods;
        this.setState({ auctions });
      }
    });
  }
  clearInpVal = () => {
    this.setState({
      searchValue: '',
      auctions: [],
      shops: [],
    })
  }
  render (){
    const { auctions, shops, searchValue } = this.state;
    // console.log(auctions);
    const columns_goods = [
      {
        title: '宝贝标题',
        dataIndex: 'raw_title',
        render: (val ,record) => <a href={record.detail_url} dangerouslySetInnerHTML={{__html: val}} target="_blank"/>,
        width:'240px'
      },
      {
        title: '宝贝标签',
        dataIndex: 'icon',
        render: (val, record) => <KXIcons icon={val} />
        
      },
      {
        title: '新七条',
        dataIndex: 'new7',
        render: (val,record) => {
          const str = record.icon && record.icon.find(item => /新7条|新七条|营销/.test(item.innerText));
          return str ? '符合' : '不符合';
        }
      },
      {
        title: '有好货入库',
        dataIndex: 'goodGoods',
      },
      {
        title: '店铺',
        dataIndex: 'shop',
        render: (val, record) => {
          const urlObj = url.parse(record.shopLink);
          const query = querystring.parse(urlObj.query);
          const shop = this.state.shops.find(item => item.userId === query.user_number_id);
          if (shop) return <a href={shop.url} target="_blank">{shop.title}</a>;
          return '';
        },
      },
      {
        title: '好评率',
        dataIndex: 'favorableRate',
        render: (val, record) => {
          const urlObj = url.parse(record.shopLink);
          const query = querystring.parse(urlObj.query);
          const shop = this.state.shops.find(item => item.userId === query.user_number_id);
          if (shop) return shop.favorableRate;
          return '';
        },
      },
      // {
      //   title: '月销',
      //   dataIndex: 'sale',
      // },
      {
        title: '售价',
        dataIndex: 'view_price',
      },
      // {
      //   title: '淘客比例',
      //   dataIndex: 'taoke',
      // },
      // {
      //   title: '淘客佣金',
      //   dataIndex: 'commission',
      // },
      {
        title: '选品池',
        dataIndex: 'pools',
        render: val => {
          if (val) {
            return val.map((item, index) =>
              <Tag closable={false} key={`pools${index}`}>
                <Tooltip placement="top" title={`${item.channel_name} / ${item.activity_name}`}>
                  <a href={item.kxuan_url_with_q} target="_blank">{item.channel_name}</a>
                </Tooltip>
              </Tag>);
          }
          return '';
        },
      },
    ];
    const columns_store = [
      {
        title: '店铺名',
        dataIndex: 'title',
        render: (val ,record) => <a href={record.url} target="_blank">{val}</a>,
      },
      // {
      //   title: '店铺标签',
      //   dataIndex: 'tags'
      // },
      {
        title: '信用等级',
        dataIndex: 'levelClasses',
        render:(val ,record) =>  <KXShopLevel levelClasses={val} />
      },
      {
        title: '好评率',
        dataIndex: 'favorableRate'
      },
      // {
      //   title: 'DSR',
      //   dataIndex: 'DSR'
      // },
      // {
      //   title: '店铺收藏',
      //   dataIndex: 'collect'
      // },
      // {
      //   title: '宝贝数',
      //   dataIndex: 'goodsSum'
      // },
      // {
      //   title: '客单价',
      //   dataIndex: 'price'
      // },
      // {
      //   title: '奢侈品',
      //   dataIndex: 'luxury'
      // },
      // {
      //   title: '精品',
      //   dataIndex: 'qualityGoods'
      // },
      // {
      //   title: '新品',
      //   dataIndex: 'new'
      // },
      // {
      //   title: '趋势品',
      //   dataIndex: 'tendency'
      // },
      // {
      //   title: '特色品',
      //   dataIndex: 'feature'
      // }
    ];
    return (
      <Card bordered={false}>
        <div className="dpcz">
          <div className={styles.searchBox} style={{ position: 'relative' }}>
            <Search
              placeholder="请输入要搜索的关键词或商品链接"
              enterButton="搜索"
              size="large"
              onSearch={this.handleSearch}
              onChange={(e) => this.setState({ searchValue: e.target.value })}
              value={searchValue}
            />
            <Icon type="close-circle" className={styles.clearInpIcon} onClick={this.clearInpVal} />
          </div>
          <div className={styles.dataList}>
            <Table
              loading={this.state.loading}
              dataSource={auctions}
              size="small"
              columns={columns_goods}
              rowKey={record => `${record.category}${record.nid}${record.kid}${Math.random()}`}
            />
            <div style={{ marginTop: 20 }}/>
            <Table
              loading={this.state.loading}
              dataSource={shops}
              size="small"
              columns={columns_store}
              rowKey="userId"
            />
          </div>
        </div>
      </Card>
    );
  }
}
